// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境
const db = cloud.database();
const _ = db.command;
// 云函数入口函数
exports.main = async (event, context) => {
    const {
        userId,
        refresh
    } = event;

    const userInfo = await db.collection('users').doc(userId).get();

    if (!userInfo.data) {
        return {
            success: false,
            message: '用户不存在'
        };
    }

    // 查询用户的所有会话
    const sessions = await db.collection('chat_sessions')
        .where({
            users: _.in([userId])
        })
        .orderBy('lastMessage.time', 'desc')
        .get();

    // 获取每个会话的用户信息
    const result = await Promise.all(sessions.data.map(async session => {
        const otherUserId = session.users[0] === userId ? session.users[1] : session.users[0];
        const otherUser = await db.collection('users').doc(otherUserId).get();

        return {
            ...session,
            nickName: otherUser.data ? otherUser.data.nickName : '未知用户',
            avatarUrl: otherUser.data ? otherUser.data.avatarUrl : '/images/default-avatar.png',
            online: otherUser.data ? otherUser.data.online : false,
            unreadCount: session.unreadCount[userId] || 0
        };
    }));

    return {
        success: true,
        data: result
    };
};